'use client';
import React, { useEffect, useRef } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
interface Iprop {
	position: any;
}

const AMapExample = ({ position }: Iprop) => {
	const mapContainer = useRef<HTMLDivElement>(null);
	useEffect(() => {
		try {
			import('@amap/amap-jsapi-loader').then((AMapLoader) => {
				AMapLoader.load({
					key: '898c78ef0e4fb352766bd7da82f10db9', // 申请好的Web端开发者Key，首次调用 load 时必填
					version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					plugins: ['AMap.Geocoder', 'AMap.InfoWindow', 'AMap.Marker', 'AMap.Pixel'] //插件列表
				})
					.then(async (AMap) => {
						// 地图添加标记
						var map = new AMap.Map(mapContainer.current, {
							resizeEnable: true,
							rotateEnable: true,
							pitchEnable: true,
							zoom: 17,
							pitch: 50,
							rotation: -15,
							viewMode: '3D', //开启3D视图,默认为关闭
							zooms: [2, 20]
						});
						var marker = new AMap.Marker();
						var geocoder = new AMap.Geocoder({ city: '010' });
						var address = position.address;
						console.log(address);
						try {
							await geocoder.getLocation(address, (status: any, result: any) => {
								console.log(status, result);

								if (status === 'complete' && result.geocodes.length) {
									var lnglat = result.geocodes[0].location;
									console.log(lnglat);

									marker.setPosition(lnglat);
									marker.setIcon('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png');
									console.log(position, 'positionpositionposition');
									console.log(marker);
									map.add(marker);
									//信息窗体的内容
									var content = [`<div><h3>${position.name}</h3><p>${position.address}</p></div>`];
									//创建 infoWindow 实例
									var infoWindow = new AMap.InfoWindow({
										content: content, //传入字符串拼接的 DOM 元素
										anchor: 'bottom-left',
										offset: new AMap.Pixel(0, -55)
										// isCustom: true, //使用自定义窗体
									});
									console.log(map.getCenter());
									//打开信息窗体
									infoWindow.open(map, marker.getPosition()); //map 为当前地图的实例，map.getCenter() 用于获取地图中心点坐标。
									marker.on('click', function () {
										infoWindow.open(map, marker.getPosition());
									});
									map.setZoomAndCenter(17, marker.getPosition());
								} else {
									console.error('根据地址查询位置失败');
								}
							});
						} catch (error) {
							console.log(error);
						}
					})
					.catch((e) => {
						console.log(e);
					});
			});
		} catch (error) {
			console.log(error);
		}
	}, [position]);

	return <div id="mapContainer" ref={mapContainer} style={{ width: '100%', height: '545px' }}></div>;
};

export default AMapExample;
